from collections import Callable

from pygame.surface import Surface

from Lib import Utils


class LocalResource:
    def __init__(self, _callable: Callable[[int, int, Surface]] = None, loaded_callable=None):
        self.resources = {}
        self.loaded_count = 0
        self.loading_callable: Callable = _callable
        self.loaded_callable: [Callable] = loaded_callable
        self.is_loaded = False

    def Load(self, scene_name):
        from constants import config
        self.path_resource = config.get("base", "scene_path") + scene_name + "/resources.json"
        self.json_data = Utils.LoadJsonFile(self.path_resource)
        self.count = len(self.json_data)
        import threading
        from Lib.Utils import Console
        Console(f"开启线程：【加载】", "import")
        self.load_threading = threading.Thread(target=self.AsyncLoad, name="loading")
        self.load_threading.start()

    def AsyncLoad(self):
        from Lib import UtilsGame
        data_json = self.json_data
        for key in data_json.keys():
            path = data_json[key]
            _resource = UtilsGame.LoadResource(path)
            self.resources[key] = _resource
            self.loaded_count += 1
            if self.loading_callable:
                self.loading_callable(self.loaded_count, self.count, _resource, path, key)

        if self.loaded_count >= len(data_json.keys()) and self.loaded_callable:
            self.is_loaded = True
            self.loaded_callable()
            from Lib.Utils import Console
            Console(f"关闭线程：【加载】", "import")

    def Get(self, resource_name):
        if resource_name not in self.resources:
            from Lib.Utils import Console
            Console(f"未找到资源: {resource_name}", "error", color=31)
        else:
            return self.resources[resource_name]
